//
//  LRXHelpeMesg.m
//  路人侠
//
//  Created by zhangxulong on 2/8/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXHelpMesg.h"
#import "LRXHelpMesgCell.h"
#import "LRXHelpMeInfoModel.h"
#import "LRXHelpMoreInfoView.h"
#import "TWTSideMenuViewController.h"
#import "LRXLMeController.h"
#import "MJRefresh.h"
#import "LRXAddrcInfoController.h"
#import "LRXTimeStamp.h"
#import <list>
#import "AppDelegate.h"
#import "LRXDistributionController.h"
#import "LRXJudgeMentController.h"
#import "LRXLoginViewController.h"
#import "LRXHelpMesgData.h"
#import "LRXChooseSexViewController.h"

using namespace std;
static NSString * const cellIdentifier = @"reUsedID";

@interface LRXHelpMesg() <
    UIGestureRecognizerDelegate,
    UITableViewDataSource,
    UITableViewDelegate,
    LRXAddrcInfoControllerDelegate,
    LRXOfflineDelegate,
    HelpMoreInfoViewDelegate,
    CAAnimationDelegate
>
{
    list<LRXHelpMeInfoModel *> helpMesgList;
}



@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,weak) LRXHelpMoreInfoView * moreView;
@property (nonatomic,weak) LRXOfflineView * OfflineViewHead;
@property (nonatomic,strong) UIPanGestureRecognizer * leftpan;


/**
 *   typeBtnState 是主按钮的动画状态
 *   typeBtnState 0 的时候 为收缩状态
 *   typeBtnState 1 的时候 为展开状态
 */
@property (nonatomic,assign) NSInteger typeBtnState;
/**
 *  MainBtnHidden 的主按钮是否隐藏
 *  MainBtnHidden 0 的时候隐藏
 *  MainBtnHidden 1 的时候动画进行中
 */
@property (nonatomic,assign) NSInteger MainBtnHidden;
/**
 *  animationStop 的收缩和展开动画时候状态
 *  animationStop 0 的时候动画结束
 *  animationStop 1 的时候动画进行中
 */
@property (nonatomic,assign) NSInteger animationStop;

@property (nonatomic,weak) UIButton * typeBtn;
@property (nonatomic,weak) NSMutableArray * picPoint;
@property (nonatomic,weak) UIView * mengban;
@property (nonatomic,weak) UIView * mengban1;
/**
 *  page 当前的页数
 */
@property (nonatomic,assign) NSInteger  page;
/**
 *  created_at 系统时间
 */
@property (nonatomic,copy) NSString * created_at;
@property (nonatomic,assign) NSInteger firstFlag;

@property (nonatomic,weak) MJRefreshStateHeader * refreshHeader;
/**
 *  lastScrollOffset 表示最后的tableView偏移量的位置
 */
@property (nonatomic,assign) CGFloat lastScrollOffset;

@property (nonatomic,weak) UIView * whiteView;

@property (nonatomic,strong) AppDelegate * appDelegate;

@property (nonatomic,assign) NSInteger deleCellRow;

@property (nonatomic,strong) LRXHelpMesgData * helpMesgData;


@end

@implementation LRXHelpMesg

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    //初始化page 为1 和时间戳
    self.page = 1;
    self.created_at = @"0000000000";
    self.firstFlag = 0;
    self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
   
  
    
    //设置导航
    [self setNavView];
    //添加手势
    [self addGestureRecognizer];
    
    CGRect tableRect =  CGRectMake(0, 0, self.view.frame.size.width, MainScreenH - NavbarH - statuesH);
    self.tableView = [[UITableView alloc]initWithFrame:tableRect style:UITableViewStylePlain];


    

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    [self.view addSubview:self.tableView];
    
    //设置tableView的属性
    [self setContentTableView];
}

#pragma mark - 设置导航
- (void)setNavView
{
    //设置标题 格式
    self.navigationItem.title = @"首页";
    UIButton * openItemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [openItemBtn setImage:[UIImage imageNamed:@"userIcon"] forState:UIControlStateNormal];
    openItemBtn.bounds = CGRectMake(0, 0,NavbarH * 0.7, NavbarH * 0.7);
    [openItemBtn addTarget:self action:@selector(openButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *openItem = [[UIBarButtonItem alloc] initWithCustomView:openItemBtn];
    
    self.navigationItem.leftBarButtonItem = openItem;
}

#pragma mark - 设置内容视图，tableView
- (void)setContentTableView
{
    __weak id weakSelf = self;
    TableViewLoadDataBlock loadDataBlock = ^(std::list<LRXHelpMeInfoModel *> items, NSArray * nextPage){
        LRXHelpMesg * strongSelf = weakSelf;
        helpMesgList = items;
        if (nextPage != nil && nextPage.count > 0){
            //已加载第一页的数据了
            strongSelf.firstFlag = 1;
            [strongSelf.tableView reloadData];
        }
        else //没有数据了
        {
            [(MJRefreshStateHeader *)self.tableView.mj_header setTitle:@"少侠没有最新数据" forState:MJRefreshStateRefreshing];
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            [(MJRefreshStateHeader *)self.tableView.mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateRefreshing];
        });
        if (items.size() < 4) {
            strongSelf.tableView.mj_footer.hidden = YES;
        }
        else
        {
            strongSelf.tableView.mj_footer.hidden = NO;
        }
    };
    
    TableViewLoadFaildBlock faildHeadBlock = ^{
        LRXHelpMesg * strongSelf = weakSelf;
        [strongSelf.tableView.mj_header endRefreshing];
    };

    TableViewLoadDataBlock moreDataBlock = ^(std::list<LRXHelpMeInfoModel *> items, NSString * nextPage){
        LRXHelpMesg * strongSelf = weakSelf;
        helpMesgList = items;
        //结束刷新
        [strongSelf.tableView.mj_footer endRefreshing];
        if (nextPage != nil && nextPage.length > 0) {
            //恢复没有数据状态
            [strongSelf.tableView.mj_footer resetNoMoreData];
            [strongSelf.tableView reloadData];
        }
        else{
            [strongSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    };
    
    TableViewLoadFaildBlock faildFooterBlock = ^{
        LRXHelpMesg * strongSelf = weakSelf;
        [strongSelf.tableView.mj_footer endRefreshing];
    };
    
    
    self.helpMesgData = [[LRXHelpMesgData alloc]initWithItemsWithLoadDatablock:loadDataBlock loadDataFaildBlock:faildHeadBlock WithMoreDataBlock:moreDataBlock moreDataFaildBlock:faildFooterBlock];
    
    LRXOfflineView * offline = [[LRXOfflineView alloc]initNoInternetWithFrame:self.view.bounds description:@"网络出错啦，请点击按钮重新加载（C7003）" canTouch:YES];
    offline.offlineDelegate = self;
    self.OfflineViewHead = offline;
    
    
    /**
     *  如果没有网的状态，就显示没有网的状态 LRXOfflineView
     */
#pragma mark 联网的判断
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if ([reach currentReachabilityStatus] == NotReachable) {
        self.tableView.tableHeaderView =  offline;
        
    }
    else
    {
        [self layoutTypeSubBtnView];
        MJRefreshStateHeader * refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self.helpMesgData refreshingAction:@selector(loadNewInfo)];
        refreshHeader.lastUpdatedTimeLabel.hidden = YES;
        self.tableView.mj_header = refreshHeader;
        //添加尾部更多
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self.helpMesgData refreshingAction:@selector(loadMoreInfo)];
        self.tableView.mj_footer.hidden = YES;
    }


    //每一个row 的高度
    self.tableView.rowHeight = 240 * hScale;
    //隐藏 滑动条
    self.tableView.showsVerticalScrollIndicator = NO;
    //加载数据
    [self.tableView.mj_header beginRefreshing];
    
    [self setExtraCellLineHidden:self.tableView];
}
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];

    
}
#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return helpMesgList.size();
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LRXHelpMesgCell * cell = [tableView dequeueReusableCellWithIdentifier:@"reUsedID"];
    //C++ 的队列的使用
    NSInteger t = 0;
    for (auto i = helpMesgList.begin(); i != helpMesgList.end(); i++){
        //查找与之对应的indexPath.section
        if (t == indexPath.row) {
            if (cell == nil) {
                cell = [[LRXHelpMesgCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reUsedID"];
                //获取list中的数据
                [cell layoutSubviews:*i];
            }
            else
                [cell setHelpMesgCellModel:*i];
            break;
        }
        t++;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.row = indexPath.row;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LRXHelpMesgCell * cell =  [tableView cellForRowAtIndexPath:indexPath];
    //当弹出 蒙板 导航栏中的左按钮不可用
    self.navigationItem.leftBarButtonItem.enabled = NO;
    UIView * backgroundView1 = [[UIView alloc]init];
    backgroundView1.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView1.frame = CGRectMake(0, 0, 640 * wScale, MainScreenH);
    //手势 点击
    UITapGestureRecognizer * pin1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mengbanClick1)];
    [backgroundView1 addGestureRecognizer:pin1];
    
    int t = 0;
    for (auto i = helpMesgList.begin(); i != helpMesgList.end(); i++) {
        
        //查找与之对应的indexPath.row
        if (t == indexPath.row) {
            //获取list中的数据
            LRXHelpMeInfoModel * model = *i;
            self.moreView = [LRXHelpMoreInfoView layoutHelpMoreView:model];
            self.moreView.row = t;
            self.moreView.helpMoreDelegate = self;
            break;
        }
        t++;
    }
    
    
    
    UIImageView * userIcon = [[UIImageView alloc]initWithImage:cell.userView.image];
    self.moreView.frame = CGRectMake(50 * wScale, 176 * hScale, MainScreenW - 2 * 50 * wScale, self.moreView.maxHeight);
    self.moreView.userIcon = userIcon;
    self.moreView.cellUserIcon = cell.userView;
    
    self.mengban1 = backgroundView1;
    CAKeyframeAnimation * bringAni = [CAKeyframeAnimation animation];
    bringAni.keyPath = @"transform.scale";
    bringAni.values = @[@0,@1];
    bringAni.duration = 0.15;
    [self.moreView.layer addAnimation:bringAni forKey:nil];
    

    [self.view addSubview:backgroundView1];
    [self.view addSubview:self.moreView];
    
}
#pragma mark - helpMoreInfoDelegate
/**
 *  点击HelpMoreInfoView 根据row 的值 来确定状态
 *
 *  @param HelpMoreInfoView HelpMoreInfoView
 *  @param row              tag -2  未登录
 *                          tag -3  未知错误
 *                          tag -4  接单到了上限
 *                          tag -5  被其他人接受
 */
- (void)helpMoreInfoAccpetBtnClick:(LRXHelpMoreInfoView *)HelpMoreInfoView withRow:(NSInteger)row withType:(NSInteger)itemType
{
    self.deleCellRow = row;

    if (itemType == -2) {
        [self pushNewController:2];
    }
    else if(itemType == -3)
    {
        [LRXOfflineView showOfflineView:@"发现未知错误" toView:self.view];
    }
    else if(itemType == -4)
    {
        [LRXOfflineView showOfflineView:@"您接单的数目已超过指定数目" toView:self.view];
    }
    else if(itemType == -5)
    {
        [LRXOfflineView showOfflineView:@"订单已被抢" toView:self.view];
        [self deleSourceDataAndCellViewWith:row];
    }
    else if(itemType == -6)
    {
        [LRXOfflineView showOfflineView:@"订单无效" toView:self.view];
        [self deleSourceDataAndCellViewWith:row];
    }
    else if(itemType == 1)
    {
        [self deleSourceDataAndCellViewWith:row];
        self.appDelegate.userRole = USERHELPERTYPR;
    }
    else if(itemType == 0)
    {
        [LRXOfflineView showOfflineView:@"自己人无效" toView:self.view];
    }
    [self mengbanClick1];
   
}

- (void)deleSourceDataAndCellViewWith:(NSInteger)row
{
    int t = 0;
    for (std::list<LRXHelpMeInfoModel *>::iterator i = helpMesgList.begin();
         i != helpMesgList.end(); i++){
        if (t == row) {
            helpMesgList.erase(i);
            break;
        }
        t++;
    }
    NSIndexPath * rowPath = [NSIndexPath indexPathForRow:row inSection:0];
    [self.tableView deleteRowsAtIndexPaths:@[rowPath] withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark - 推出新的控制器（登录）
- (void)pushNewController:(NSInteger)controllerType
{
    //登录
    if(controllerType == 2)
    {
        CATransition* transition = [CATransition animation];
        transition.type = kCATransitionPush;//可更改为其他方式
        transition.subtype = kCATransitionFromTop;//可更改为其他方式
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:[LRXLoginViewController new] animated:NO];
    }
}
#pragma mark - 打开侧边栏
- (void)openButtonPressed
{
    [self.sideMenuViewController openMenuAnimated:YES completion:nil];
}


#pragma mark - 不同类型的按钮 的分布
- (void)layoutTypeSubBtnView
{
    self.typeBtnState = 0;
    self.MainBtnHidden = 1;

    UIButton * typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //分功能显示 按钮
    [typeBtn setImage:[UIImage imageNamed:@"duigou"] forState:UIControlStateNormal];
    typeBtn.backgroundColor = mainColor;
    typeBtn.frame = CGRectMake(502 * wScale,MainScreenH - 300 * hScale, 100 * wScale, 100 *wScale);
    typeBtn.center = CGPointMake(MainScreenW - 100 * wScale, MainScreenH - 250 * hScale);
    typeBtn.layer.cornerRadius = typeBtn.bounds.size.width * 0.5;
    typeBtn.imageEdgeInsets = UIEdgeInsetsMake(30 * hScale, 30 * hScale, 30 * hScale, 30 * hScale);
    [typeBtn addTarget:self action:@selector(pushMeHelpView) forControlEvents:UIControlEventTouchUpInside];
    self.typeBtn = typeBtn;
    [self.view addSubview:typeBtn];
}

#pragma mark - 推出求带界面
- (void)pushMeHelpView
{
    
    if(self.appDelegate.userRole == USEROFFLINETYPE)
    {
        [self pushNewController:2];
    }
    else if(self.appDelegate.userRole == USERHELPERTYPR || self.appDelegate.userRole == USERNORMALTYPE )
    {
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        NSString * firstPushMesg = [defaults objectForKey:@"firstPushMesg"];
        if ([firstPushMesg isEqualToString:@"1"]) {
            LRXLMeController * LMeHeplerController = [[LRXLMeController alloc]init];
            [self.navigationController pushViewController:LMeHeplerController animated:YES];
        }
        else
        {
            [defaults setObject:@"1" forKey:@"firstPushMesg"];
            [defaults synchronize];
            
            [self presentViewController:[LRXChooseSexViewController new] animated:YES completion:nil];
        }
  


    }
    else{
        [LRXOfflineView showOfflineView:@"正在获取身份" toView:self.view];
    }
}

#pragma mark - 移除 求带详细信息 的蒙板和View
- (void)mengbanClick1
{
    //当移除 蒙板 导航栏中的左按钮不可用
    self.navigationItem.leftBarButtonItem.enabled = YES;
    
    //收缩动画
    CAKeyframeAnimation * moreAni = [CAKeyframeAnimation animation];
    moreAni.keyPath = @"transform.scale";
    moreAni.values = @[@1,@0];
    moreAni.duration = 0.15;
    moreAni.removedOnCompletion=NO;
    moreAni.fillMode=kCAFillModeForwards;
    
    [self.moreView.layer addAnimation:moreAni forKey:nil];
    
    //延时删除
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.mengban1 removeFromSuperview];
        [self.moreView removeFromSuperview];
    });
    
    
}

#pragma mark - offflineDelegate
-( void )didTouchOfflineView
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    NSLog(@"网络状态：%ld",[reach currentReachabilityStatus]);
    if([reach currentReachabilityStatus ] != NotReachable)
    {
        //重新刷新数据 刷新
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.tableHeaderView = nil;
            [self setContentTableView];
            [self.appDelegate getUserRole];
            [self.tableView reloadData];
        }];
        
    }
}
- (void)didTouchNoDataView
{
    
}
#pragma mark - GestureRecognizer
- (void)addGestureRecognizer
{
    self.leftpan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(openButtonPressed)];
    self.leftpan.delegate = self;
    [self.view addGestureRecognizer:self.leftpan];
    
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint start = [gestureRecognizer locationInView:self.view];
    if (start.x <= 100 * wScale) {
        return YES;
    }
    else
        return  NO;
}

#pragma mark - scrollViewDelegate
//当滚动的时候 主按钮隐藏动画
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    CGFloat y = scrollView.contentOffset.y;

    /**
     *  向上滑动 隐藏
     */
    if (y > (self.lastScrollOffset) + 10 * wScale) {
        if (self.MainBtnHidden == 1) {

            self.MainBtnHidden = 0;
            CAKeyframeAnimation * mainBtnAni = [CAKeyframeAnimation animation];
            mainBtnAni.keyPath = @"position";
            [mainBtnAni setValue:@"mainBtnAniHidden" forKey:@"mainBtnAniHidden"];

            CGPoint endPoint = CGPointMake(self.typeBtn.center.x, MainScreenH + 100 * hScale);
            mainBtnAni.values = @[[NSValue valueWithCGPoint:self.typeBtn.center],[NSValue valueWithCGPoint:endPoint]];

            mainBtnAni.removedOnCompletion = NO;
            mainBtnAni.fillMode = kCAFillModeForwards;
            mainBtnAni.delegate = self;
            self.typeBtn.center = endPoint;
            [self.typeBtn.layer addAnimation:mainBtnAni forKey:nil];

        }

    }
    /**
     *  向下滑动  显示
     */
    else if(y < (self.lastScrollOffset) - 10 * wScale){
        if (self.MainBtnHidden == 0) {
            self.MainBtnHidden = 1;
            CAKeyframeAnimation * mainBtnAni = [CAKeyframeAnimation animation];
            mainBtnAni.keyPath = @"position";
            [mainBtnAni setValue:@"mainBtnAniShow" forKey:@"mainBtnAniShow"];

            CGPoint endPoint = CGPointMake(self.typeBtn.center.x, MainScreenH - 250 * hScale);
            mainBtnAni.values = @[[NSValue valueWithCGPoint:self.typeBtn.center],[NSValue valueWithCGPoint:endPoint]];

            mainBtnAni.removedOnCompletion = NO;
            mainBtnAni.fillMode = kCAFillModeForwards;
            mainBtnAni.delegate = self;
            self.typeBtn.center = endPoint;
            [self.typeBtn.layer addAnimation:mainBtnAni forKey:nil];
        }
    }
    self.lastScrollOffset = y;
    
}
@end
